package com.cuij.controller.dofilecontroller;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/busi")
public class busiUploadImgController {

    @RequestMapping("/busiuploadImg.do")
    @ResponseBody
    public Object uploadImg(@RequestParam("busifile") MultipartFile busifile, HttpServletRequest request,
            HttpServletResponse response)
            throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        // PrintWriter out = response.getWriter();
        Map<String, Object> resMap = new HashMap<String, Object>();
        SimpleDateFormat simpleFormat = new SimpleDateFormat("MMddHHmmsss");
        String generationfileName = simpleFormat.format(new Date()) + new Random().nextInt(1000);
        // 文件保存的路径
        String savePath = "D:/MeCode/SchoolOrder/WebRoot/busipics";
        String fileNameSuffix = null;
        String fileName = null;

        try {
            fileName = busifile.getOriginalFilename();
            if (null != busifile && !"".equals(busifile)) {

                fileNameSuffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
                SaveFileFromInputStream(busifile.getInputStream(), savePath, generationfileName + "." + fileNameSuffix);
                fileName = generationfileName + "." + fileNameSuffix;
                resMap.put("status", "0");
                resMap.put("data", fileName);
                resMap.put("msg", "上传成功");
            }

        }
        catch (Exception e) {
            resMap.put("status", "1");
            resMap.put("msg", "上传失败");
            e.printStackTrace();
        }
        return resMap;
    }

    private void SaveFileFromInputStream(InputStream stream, String path, String filename) throws IOException {
        FileOutputStream fs = new FileOutputStream(path + "/" + filename);
        byte[] buffer = new byte[1024 * 1024];
        int bytesum = 0;
        int byteread = 0;
        while ((byteread = stream.read(buffer)) != -1) {
            bytesum += byteread;
            fs.write(buffer, 0, byteread);
            fs.flush();
        }
        fs.close();
        stream.close();

    }
}
